<template>
  <div class="app-container">
    <div class="top-main">
    <el-form  class="top-form-fl" :model="param" label-width="auto" :inline="true">   
      <el-form-item label="购箱城市">
        <city-select :selectCity="param.carryCityId" @cityId="startCityId" style="width: 100%;"></city-select>
      </el-form-item>
      <el-form-item label="创建日期">
        <el-date-picker v-model="param.createDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="编号">
        <el-input v-model.trim="param.releaseNo" clearable placeholder="请输入" style="width: 300px;"></el-input>
      </el-form-item>
    </el-form>
    <div class="top-from-fr">
        <el-button class="top-Search" @click="getTableData" type="primary">搜索</el-button>
        <el-button class="top-Refresh" @click="handleReSet">重置</el-button>
      </div>   
    </div>
    <cz-tages :bottomLine="true" :typeList="param.typeList" @handleTypeChange="handleTypeChange"></cz-tages>
    <span style="float: right;">
      <el-button :icon="Delete" type="danger" size="small" round @click="isDelete($event, 'pitch')" plain>批量删除</el-button>
      <el-button :icon="Download" type="info" size="small" round @click="boxDown($event, 'pitch')" plain>批量下架</el-button>
      <el-button :icon="Upload" type="primary" size="small" round @click="boxPublish($event, 'pitch')" plain>批量上架</el-button>
      <el-button :icon="Promotion" type="success" size="small" round @click="goBuybox" plain>发布</el-button>
    </span>

    <Table ref="tableRef" v-bind="table" :disableHeaderCheckbox="false" @pageChange="onTablePageChange" @activEdit="activEdit" @boxPublish="boxPublish"
      @boxDown="boxDown" @showInfo="showInfo" @isDelete="isDelete">
    </Table>

    <!-- dialog -->
    <el-dialog v-model="param.dialogVisible" title="系统提示" width="500">
      <span>确认删除？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="activDelete">是的</el-button>
          <el-button type="primary" @click="param.dialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import Table from '@/components/table'
import czTages from '@/components/chengzhiTags'
import citySelect from '@/components/citySelect'
import orderInfo from '@/store/modules/order'
import { wantBuySelectSelfPage, downPitch, publishPitch, deletePitch ,statusCount} from '@/api/boxDeal/boxSeel'
import { computed, onActivated, onMounted, reactive, ref } from 'vue';
import { Plus, Delete, Promotion, Edit, Message, Download, Upload } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const param = reactive({
  loading: false,
  pageNum: 1,
  pageSize: 10,
  dialogVisible: false,
  stateFilter: { 5: '求购中', 10: '仓库中', 15: '待发布' },
  stateColor: { 5: '#22A86D', 10: '#2158F3', 15: '#2158F3' },
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提(次新或者适货)', },
    { value: '5', label: '全新', },
  ],
  beginTotalRentQty: '',
  endTotalRentQty: '',
  releaseNo:"",
  createDate:"",
  createTime:"",
  startCityOptions: [],
  backCityOptions: [],
  typeList: [],
  carryCityId:""
});


const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'releaseNo', colWidth: '200', title: '编号', type: '<change>', command: 'showInfo', isCheck: true },
    { key: 'carryCityName', colWidth: '350', title: '购箱城市', type: 'cityName', isCheck: true, isHuidiao: true },
    { key: 'minUnitPrice', colWidth: '100', title: '求购价格', type: 'add', currency: 'minUnitPriceCurrency', isCheck: true },
    { key: 'totalInventoryQty', colWidth: '100', title: '求购箱量', type: 'add', after: '个',isTooltip: true,tooltip: "求购各箱型箱况求购箱数量之和", isCheck: true },
    { key: 'status', colWidth: '100', title: '发布状态', type: 'filter', filter: param.stateFilter, cFilter: param.stateColor, isCheck: true },
    { key: 'createTime', colWidth: '200', title: '创建日期', sortable: true, type: 'dateTime', isCheck: true },
    { key: 'updateTime', colWidth: '200', title: '更新日期', sortable: true, type: 'dateTime', isCheck: true },
    {
      key: 'operate',
      colWidth: '250',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // content: '编辑',
          // icon: 'Edit',
          command: 'activEdit',
          name: '编辑',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '下架',
          // icon: 'Download',
          command: 'boxDown',
          name: '下架',
          isShow: (row: { status: string; }) => {
            return row.status == '5';
          },
        },
        {
          // content: '上架',
          // icon: 'Upload',
          command: 'boxPublish',
          name: '上架',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },
        {
          // content: '删除',
          // icon: 'Delete',
          command: 'isDelete',
          name: '删除',
          isShow: (row: { status: string; }) => {
            return row.status != '5';
          },
        },

      ],
    },
    // { key: 'totalRentQty', colWidth: '150', title: '12312', isTooltip: true, tooltip: "箱回调需求自发布上架以来，回调成功的订单的集装箱总数（不含回调中/回调后退款成功的订单）", sortable: true, type: 'text', isCheck: true },
    // { key: 'total30RentQty', colWidth: '150', title: '30天回调量', isTooltip: true, tooltip: "计算近30天的回调箱量，回调箱量数据有1天延迟", sortable: true, type: 'text', isCheck: true },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  }
});

onActivated(() => {
  getTableData()
});

const startCityId = (id: string) => {
  param.carryCityId = id
}
const backCityId = (id: string) => {
  param.returnCityIds = id
}

function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

function getTableData() {
  let data = {
    releaseSource:'10', //5-售箱公司发布 10-求购箱公司发布
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    carryCityId:param.carryCityId,
    releaseNo: param.releaseNo?.toUpperCase() || "",
    beginCreateDate:"",
    endCreateDate:"",
    // beginTotalRentQty: param.beginTotalRentQty - 0 || "",
    // endTotalRentQty: param.endTotalRentQty - 0 || "",
    status: param.status - 0 || null
  };
  if (param.createDate) {
    data.beginCreateDate = param.createDate[0];
    data.endCreateDate = param.createDate[1];
  }
  // table.config.loading = true;
  // 列表
  wantBuySelectSelfPage(data).then((res: any) => {
    const list = res.data.list;
    formatCityInfo(list)
    table.data = list
    table.config.total = res.data.total;
  });

   //汇总
  data.rentSource = 10 // 租箱来源: 5 - 集装箱公司发布  10- 货代发布
  statusCount(data).then((res: { data: any }) => {
      const resList = res.data // [ { status: 5, totalQty: 0 },{ status: 10, totalQty: 0 },{ status: 15, totalQty: 0 } ]
      const list = [{ id: 0, name: '全部', num: 0 }, { id: 5, name: '出售中', num: 0 }, { id: 10, name: '仓库中', num: 0 }, { id: 15, name: '待发布', num: 0 }]
      param.typeList = formatStateCount(list, resList)
      table.config.loading = false;
  })

}
//重置
function handleReSet() {
  param.carryCityIds = null
  param.returnCityIds = null
  param.beginTotalRentQty = null
  param.endTotalRentQty = null
  param.createDate = null
  param.carryCityId = null
  param.releaseNo = null
  getTableData()
}


//编辑
const router = useRouter();
const activEdit = (row: any) => {
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push({
    path: 'publishPurchase',
  })
};
const showInfo = (row: any) => {
  row.isInfo=true
  if (row) {
    orderInfo().setRowData(row)
  }
  router.push({
    path: 'publishPurchase',
  })
};
const goBuybox = () =>{
  router.push({
    path: "publishPurchase",
    query: {
      type:"release"
    }
  })
}

//上架/下架  
const tableRef = ref({ multipleSelection: [] })
const selection = computed(() => {
  let ids: any[] = []
  tableRef.value.multipleSelection.map((item: any) => {
    ids.push(item.id)
  })
  return ids
})
const boxPublish = (row: { id: any }, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要上架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  publishPitch(ids).then(() => {
    getTableData()
  })
};
const boxDown = (row: any, opt: string) => {
  let ids: any[] = []
  if (opt == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要下架的订单')
    }
    ids = selection.value
  } else {
    ids = [row.id]
  }
  downPitch(ids).then((res: any) => {
    getTableData()
  })
};

//删除 
let deleteList = ref([])
const isDelete = (row: any, opr: any) => {
  if (opr == 'pitch') {
    if (selection.value.length == 0) {
      return ElMessage.warning('请选择要删除的订单')
    }
    deleteList.value = selection.value
  } else {
    deleteList.value = [row.id]
  }
  param.dialogVisible = true;
};
const activDelete = () => {
  let ids = [...deleteList.value]
  // console.log(ids)
  deletePitch(ids).then((res: any) => {
    getTableData()
  })
  param.dialogVisible = false;
};


//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};


onMounted(() => {
  getTableData()
})


// 功能函数
const formatStateCount = (stateList: any, resList: any) => {
  let total = 0;
  stateList.forEach(item => {
    resList.forEach((obj: { status: number; totalQty: number }) => {
      if (item.id == obj.status) {
        item.num = obj.totalQty
        total += obj.totalQty
      }
    })
  })
  stateList.map(obj => {
    if (obj.id == 0) {
      obj.num = total
    }
  })
  return stateList
};

// const formatCityInfo = (list: any) => {
//   list.forEach((item: any) => {
//     // 城市
//     let carryCity = JSON.parse(item.carryCity)
//     let returnCity = JSON.parse(item.returnCity)
//     let carryCityListString = ''
//     let returnCityListString = ''
//     carryCity.map((item: any, index: number) => {
//       let dos = index == 0 ? '' : '/'
//       carryCityListString = carryCityListString + dos + item.cityName
//     })
//     returnCity.map((item: any, index: number) => {
//       let dos = index == 0 ? '' : '/'
//       returnCityListString = returnCityListString + dos + item.cityName
//     })
//     item.carryCityListString = carryCityListString
//     item.returnCityListString = returnCityListString
//     // 图片
//     let mainFileList = JSON.parse(item.mainFileList);
//     item.imgUrl = mainFileList.map((item: any) => {
//       return item.url
//     })[0];
//   })

// }

const formatCityInfo = (list: any) => {
  list.forEach((item: any) => {
    // 图片
    let mainFileList = JSON.parse(item.mainFileList);
    item.imgUrl = mainFileList.map((item: any) => {
      return item.url
    })[0];
  })

}

</script>